import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.util.NoSuchElementException;

/**
 * 
 * Contains a list of Player objects, along with a method to read them in from a file.
 *
 */
public class PlayerList extends BaphiList {
	
	/**
	 * Contains a list of Player objects, along with a method to read them in from a file.
	 * @param fileName
	 * @param commodities - Commodity list
	 * @throws FileNotFoundException
	 * @throws NoSuchElementException
	 */
	public PlayerList(String fileName, CommodityList commodities) throws FileNotFoundException, NoSuchElementException
	{
		readPlayersFromFile(fileName, commodities);
	}
	
	/**
	 * @return Player
	 */
	public Player get(int idx)
	{
		return (Player) super.get(idx);
	}
	
	/**
	 * Reads Planyers from the specified file path and populates the PlayerList
	 * @param fileName
	 * @param commodities - Commodity list
	 * @throws FileNotFoundException
	 * @throws NoSuchElementException
	 */
	private void readPlayersFromFile(String fileName, CommodityList commodities)
		throws FileNotFoundException, NoSuchElementException
	{
		File file = new File(fileName);
		Scanner scan;
		String playerName, shipName;
		int location;
		int cargoCapacity;
		
		scan = new Scanner(file);
		scan.useDelimiter(",|\n");
		
		while(scan.hasNext())
		{	
			playerName = scan.next();
			shipName = scan.next();
			cargoCapacity = scan.nextInt();
			location = scan.nextInt();
			
			Player newPlayer = new Player(playerName, shipName, location, cargoCapacity, commodities.size());
			
			this.add(newPlayer);
			
			// Read this player's starting Commodities and add them to the ship's cargo hold
			String str = scan.nextLine();
			Scanner strScan = new Scanner(str);
			strScan.useDelimiter(",|\n");
			
			while (strScan.hasNext())
			{
				String comm = strScan.next();
				int commIdx = commodities.lookup(comm);
				if (commIdx != -1)
					newPlayer.ship.cargoHold.load(commIdx, 1);
			}
			
			strScan.close();
		}
		
		scan.close();
	}
}
